﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

using Bpms.Data;
using Bpms.Entity;
using Bpms.Log;
using Bpms.Common;

namespace Bpms.Data.SqlServer
{
    public partial class DataProvider : IDataProvider
    {
        #region Private

        string customerClassName = "Bpms.Data.SqlServer.Customer";

        /// <summary>
        /// 绑定数据到客户实体
        /// </summary>
        /// <param name="idr">idatareader</param>
        /// <returns>IList<CustomerInfo>对象</returns>
        IList<CustomerInfo> GetDataBindedCustomer(IDataReader idr)
        {
            IList<CustomerInfo> customerList = new List<CustomerInfo>();

            while (idr.Read())
            {
                var customer = new CustomerInfo();

                // 基本信息
                customer.CustomerID = (int)idr["customer_id"];          // 标识ID（客户ID）
                customer.Name = idr["name"].ToString();                 // 客户名称
                customer.Number = idr["number"].ToString();             // 项目编号缩写
                customer.IsPO = (bool)idr["is_po"];                     // 是否PO流程（false：否，true：是）
                customer.IsOther = (bool)idr["is_other"];               // 是否其他结帐必须资料(false：否，true：是)
                customer.FirstCooperationTime = TimeFormat.Time_T2DateTime(Convert.ToInt64(idr["first_cooperation_time"]));  // 首次合作日期
                customer.Industry = idr["industry"].ToString();         // 行业领域
                customer.WebSite = idr["website"].ToString();           // 公司网址
                customer.Address = idr["address"].ToString();           // 公司地址
                customer.Developer = (int)idr["developer"];             // 开发人，用户ID
                customer.CheckOutCycle = (byte)idr["check_out_cycle"];  // 结帐周期(1：单，2：月，3：周)
                customer.Remark = idr["remark"].ToString();             // 备注
                customer.AddTime = TimeFormat.Time_T2DateTime(Convert.ToInt64(idr["add_time"]));        // 添加时间
                customer.UserID = (int)idr["user_id"];                  // 添加人
                customer.IsDelete = (bool)idr["is_delete"];             // 是否删除（false：否，true：是）

                customerList.Add(customer);
            }

            return customerList;
        }

        /// <summary>
        /// 根据sql语句返回客户信息
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns>客户对象</returns>
        CustomerInfo GetCustomerBySQL(string sql)
        {
            var customerList = GetCustomerListBySQL(sql);

            if (customerList.Count > 0)
            {
                return customerList[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据sql语句返回客户列表
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns> IList<CustomerInfo>对象</returns>
        IList<CustomerInfo> GetCustomerListBySQL(string sql)
        {
            IList<CustomerInfo> customerList = new List<CustomerInfo>();

            using (var idr = DbHelper.ExecuteReader(CommandType.Text, sql) as IDataReader)
            {
                try
                {
                    customerList = GetDataBindedCustomer(idr);
                }
                catch (Exception e)
                {
                    log.WriteLog(this.customerClassName + "：获取绑定的客户信息时出现异常", e);
                }
                finally
                {
                    if (idr != null)
                    {
                        idr.Close();
                    }
                }
            }

            return customerList;
        }

        #endregion

        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="customer">客户实体</param>
        /// <returns>添加是否成功（true：成功，false：失败）</returns>
        public bool InsertCustomer(CustomerInfo customer)
        {
            return true;
        }

        /// <summary>
        /// 修改客户
        /// </summary>
        /// <param name="customer">客户实体</param>
        /// <returns>修改是否成功（true：成功，false：失败）</returns>
        public bool UpdateCustomer(CustomerInfo customer)
        {
            return true;
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="customerId">客户ID</param>
        /// <returns>删除是否成功（true：成功，false：失败）</returns>
        public bool DeleteCustomer(int customerId)
        {
            return true;
        }

        /// <summary>
        /// 判断客户名称是否存在
        /// </summary>
        /// <param name="customer">客户实体</param>
        /// <param name="type">判断的类型（添加或修改）</param>
        /// <returns>客户名称是否存在（true：已存在，false：未存在）</returns>
        public bool CustomerExists(CustomerInfo customer, OperateType type)
        {
            return true;
        }

        /// <summary>
        /// 得到客户信息
        /// </summary>
        /// <param name="customerId">客户ID</param>
        /// <returns>客户信息</returns>
        public CustomerInfo GetCustomer(int customerId)
        {
            return null;
        }

        /// <summary>
        /// 得到客户列表
        /// </summary>
        /// <param name="pageId">当前页ID</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="condition">提取的条件</param>
        /// <returns>客户列表</returns>
        public IList<CustomerInfo> GetCustomers(int pageId, int pageSize, string condition)
        {
            return null;
        }

        /// <summary>
        /// 得到客户列表
        /// </summary>
        /// <param name="condition">提取的条件</param>
        /// <returns>客户列表</returns>
        public IList<CustomerInfo> GetCustomers(string condition)
        {
            StringBuilder sbSql = new StringBuilder();

            sbSql.Append(" SELECT customer_id, name, number, is_po, is_other, first_cooperation_time, industry, ");
            sbSql.Append(" website, address, developer, check_out_cycle, remark, add_time, [user_id], is_delete ");
            sbSql.Append(" FROM bp_customer ");
            sbSql.Append(" WHERE is_delete = 0 ");

            if (condition.Trim() != "")
            {
                sbSql.Append(" AND ").Append(condition);
            }
            sbSql.Append(" ORDER BY customer_id ASC ");

            try
            {
                return GetCustomerListBySQL(sbSql.ToString());
            }
            catch (Exception e)
            {
                log.WriteLog(this.customerClassName + "：得到满足条件的客户时出现异常", e);
                return null;
            }
        }        
    }
}
